package com.apes.fn.server.servicePlan.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.fn.pi.fnCommunal.FnCommunalService;
import com.apes.fn.scm.merchant.settlement.service.FeeRateService;
import com.apes.fn.server.servicePlan.model.ServicePlan;
import com.apes.fn.server.servicePlan.model.ServicePlanItem;
import com.apes.fn.server.servicePlan.repository.ServicePlanDao;
import com.apes.fn.server.servicePlan.repository.ServicePlanRepository;
import com.apes.fn.server.workOrder.repository.MaintenanceOrderRepository;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.jpa.spec.model.Filter;
import com.apes.framework.jpa.spec.model.Group;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.event.Listener;
import com.apes.framework.plugin.soe.store.database.repository.BusinessAttributeValueRepository;
import com.apes.framework.util.Arith;
import com.apes.framework.util.MapUtil;
import com.apes.pi.service.PiManager;
import com.apes.scm.masterdata.car.model.CarServiceLevel;
import com.apes.scm.masterdata.car.service.CarConfigurationService;
import com.apes.scm.masterdata.car.service.CarServiceLevelService;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import com.apes.scm.masterdata.enumeration.repository.EnumerationRepository;
import com.apes.scm.masterdata.finance.model.CooperateType;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.frame.model.Store;
import com.apes.scm.masterdata.frame.repository.DeptRepository;
import com.apes.scm.masterdata.frame.repository.OrganizationRepository;
import com.apes.scm.masterdata.frame.repository.StoreRepository;
import com.apes.scm.masterdata.merchant.model.Merchant;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.repository.AccessProviderRepository;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import com.apes.scm.masterdata.party.service.PartyRoleService;
import com.apes.scm.masterdata.product.model.Category;
import com.apes.scm.masterdata.product.model.Product;
import com.apes.scm.masterdata.product.model.ProductUom;
import com.apes.scm.masterdata.product.model.StarProduct;
import com.apes.scm.masterdata.product.repository.*;
import com.apes.scm.masterdata.product.service.ProductNegativeSellingService;
import com.apes.scm.masterdata.stock.model.Location;
import com.apes.scm.masterdata.stock.repository.LocationRepository;
import com.apes.scm.masterdata.stock.service.LocationService;
import com.apes.scm.rbac.model.Post;
import com.apes.scm.rbac.repository.PostRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StopWatch;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * Creator: zouyc
 * CreateDate: 2020-01-06 15:41
 * Description:
 **/
@Service("serviceToForeign")
public class ServiceToForeign extends PriceConditionService {
    @Autowired
    PiManager piManager;
    @Autowired
    LocationRepository locationRepository;
    @Autowired
    ProductUomRepository productUomRepository;
    @Autowired
    PartyRoleRepository partyRoleRepository;
    @Autowired
    OrganizationRepository organizationRepository;
    @Autowired
    ServeTypeRepository serveTypeRepository;
    @Autowired
    ProductRepository productRepository;
    @Autowired
    CategoryRepository categoryRepository;
    @Autowired
    DeptRepository deptRepository;
    @Autowired
    ServicePlanDao servicePlanDao;
    @Autowired
    ServicePlanRepository servicePlanRepository;
    @Autowired
    StarProductRepository starProductRepository;
    @Autowired
    ProductNegativeSellingService productNegativeSellingService;

    @Autowired
    ServicePlanceService servicePlanceService;


    @Value("${apes.switched:false}")
    private Boolean switched;

    /**
     * 方案做单选商品
     *
     * @param simpleRequest
     * @return
     */
    @Listener(topic = "event:serviceToForeign.getPrice")
    public JSONObject getPrice(SimpleRequest simpleRequest) {
        //前端入参
        JSONObject getJo = simpleRequest.getJO();
        JSONObject condition = getJo.getJSONObject("condition");
        JSONObject conditionModel = getJo.getJSONObject("conditionModel");
        if (condition == null || conditionModel == null)
            throw new RuntimeException("传入参数有误:condition/conditionModel,无此类型");
        // 获取用户选择得配件
        JSONObject fitting = new JSONObject();
        if (condition.containsKey("fitting"))
            fitting = condition.getJSONObject("fitting");
        //商品数据
        Product product = getProduct(condition);
        checkProduct(product);
        //门店数据
        Dept belongDept = getDept("belongDept",conditionModel);
        Dept saleDept = getDept("saleDept",conditionModel);
        if(conditionModel.getJSONObject("serveType")!=null&&conditionModel.getJSONObject("serveType").getString("id").equals("ServicePlan.serveType.B")){
            saleDept=belongDept;
        }
        //车辆数据
        JSONObject carJson = conditionModel.getJSONObject("customerCar");
        if (carJson == null) throw new RuntimeException("该车辆信息有误");
        //会员数据
        JSONObject fnCustomer = conditionModel.getJSONObject("customer");
        if (fnCustomer == null) throw new RuntimeException("该会员信息有误，未找到该门店");
        //合作类型
        String cooperateTypeId = judgeString("cooperationType", "id", conditionModel);
        CooperateType cooperateType = null;
        if (cooperateTypeId != null)
            cooperateType = MapUtil.getO(MapUtil.mapper("id", cooperateTypeId), CooperateType.class);
        ProductUom uom = new ProductUom();
        try {
            uom = productUomRepository.findAll(
                    JpaDsl.toCriteriaByEq("uomCategory.id", product.getUom().getUomCategory().getId(), "saleFirst", true)
            ).stream().findFirst().get();
        } catch (Exception e) {
            throw new RuntimeException("系统中不存在该商品默认销售计量单位:" + uom.getName());
        }
        //平台
        PartyRole platform = SpringManager.getBean(FnCommunalService.class).getPlatform(false, true, belongDept, product);

        //判断车型是否能做该商品
        if ("10".equals(product.getProductGroup().getId()))
            checkCarLimitType(carJson, product, belongDept); //判断车新是否停止服务，不允许做单

        JSONObject resultJsonReback = null;
        JSONObject json = new JSONObject();
        json.put("deptId", belongDept.getId());
        json.put("productId", product.getId());
        double planKys = servicePlanDao.queryLocalStore(json);
        if (belongDept.getId().equals(saleDept.getId())) {
            resultJsonReback = getXS51(getXS51Map(belongDept,product,cooperateType,carJson,fnCustomer,platform,uom,planKys),false);
//            resultJsonReback = getXS51OrXJ51(new ConditionBuilder.Builder("XS51")
//                    .setDept(belongDept)
//                    .product(product)
//                    .fnCustomer(carJson)
//                    .setPlatform(platform)
//                    .sysNoCheck("SUPPLIER_ID")
//                    .setProductUomId(uom.getId())
//                    .setCooperationType(cooperateType)
//                    .setUsableQty(planKys).build().execConditionStrategy().getResultJson());
            resultJsonReback.put("assistType", SpringManager.getBean(BusinessAttributeValueRepository.class).findOne("ServicePlanItem.assistType.normal"));

        } else {  //基地（内协方）做单调用（配件）
            resultJsonReback = getGS51(getGS51Map(belongDept,saleDept,product,platform,uom,fnCustomer,carJson));
//            resultJsonReback = getGS51PriceItem(new ConditionBuilder.Builder("GS51")
//                    .setDept(belongDept)
//                    .product(product)
//                    .fnCustomer(carJson)
//                    .setPlatform(platform)
//                    .sysNoCheck("SUPPLIER_ID")
//                    .setCustomerId(SpringManager.getBean(PartyRoleService.class)
//                            .findByPartyAndRole(saleDept.getCompany().getParty().getId(), "Customer").getId())
//                    .setProductUomId(uom.getId())
//                    .setUsableQty(planKys).build().execConditionStrategy().getResultJson().toJSONString());
            resultJsonReback.put("assistType", SpringManager.getBean(BusinessAttributeValueRepository.class).findOne("ServicePlanItem.assistType.inner"));
        }

        if (resultJsonReback == null) throw new RuntimeException("获取价格失败");
        if (productNegativeSellingService.isProductNegativeSelling(product.getId())) resultJsonReback.put("priceUnit",Arith.add(resultJsonReback.getDouble("priceUnit"),99));  // 商品负卖
        return getResultJson(conditionModel, fitting, product, belongDept, uom, platform, resultJsonReback);
    }

    /**
     * 获取内协成本
     * @param request
     * @return
     */
    public PageImpl getGS51Price(SimpleRequest request){
        JSONArray result = new JSONArray();
        JSONObject getJo = request.getJO();
        JSONObject conditionModel = getServerFiled(getJo.getJSONObject("conditionModel"));
        JSONObject node = getJo.getJSONObject("conditionModel").getJSONObject("node");
        JSONObject productJson = node.getJSONObject("product");
        JSONArray condition = getJo.getJSONArray("condition");
        //商品数据
        Product product = getProduct(productJson);
        //门店数据
        Dept belongDept = getDept("belongDept",conditionModel);
        if (condition.size()==0){
            List<Map> servicePlanItems = SpringManager.getBean(MaintenanceOrderRepository.class).findInnerMaintenanceOrderByDept(belongDept.getId(), product.getId());
            if (servicePlanItems.size()==0)throw new RuntimeException("没有找到对应商品内协数据!!!");
            List<Map> resultList = servicePlanItems.stream()
                    .filter(o -> Double.valueOf(String.valueOf(o.get("REFERTAX"))) != 0D)
                    .map(servicePlanItem -> MapUtil.mapper(
                            "itemId", node.getString("id"),
                            "dept", MapUtil.mapper("id", servicePlanItem.get("DEPT_ID"),"name", servicePlanItem.get("DEPT_NAME")),
                            "innerReferTax", servicePlanItem.get("REFERTAX"),
                            "productId", product.getId())
                    ).collect(Collectors.toList());

            return SpringManager.getBean(ServicePlanceService.class).pageInfo(getJo,resultList,false);
        }
        String deptId = condition.getJSONObject(0).getString("value");
        //这里门店取反是模拟内协时的关系转换 才能通过gs51获取正确价格
        Dept saleDept = belongDept;
        belongDept = deptRepository.findOne(deptId);
        if (belongDept == null) throw new RuntimeException("该门店有误，未找到该门店");
        //车辆数据
        JSONObject carJson = conditionModel.getJSONObject("customerCar");
        if (carJson == null) throw new RuntimeException("该车辆信息有误");
        //会员数据
        JSONObject fnCustomer = conditionModel.getJSONObject("customer");
        if (fnCustomer == null) throw new RuntimeException("该会员信息有误，未找到该门店");

        ProductUom uom = getProductUom(product);
        //平台
        PartyRole platform = SpringManager.getBean(FnCommunalService.class).getPlatform(false, true, belongDept, product);

        JSONObject json = new JSONObject();
        json.put("deptId", belongDept.getId());
        json.put("productId", product.getId());
        JSONObject resultJsonReback = getGS51(MapUtil.mapper(
                "SPID", product.getId(),
                "PZID", product.getBrand().getQuality() == null ? null : product.getBrand().getQuality().getCode(),
                "PLID", product.getClassify().getId(),
                "GSID", belongDept.getCompany().getId(),
                "YYMS", saleDept.getCompany().getParty().getCorporate().getOperation().getCode(),
                "KHID", SpringManager.getBean(PartyRoleService.class)
                        .findByPartyAndRole(saleDept.getCompany().getParty().getId(), "Customer").getId(),
                "CGZZID", platform.getId(),
                "JLDW", uom.getName(),
                "SYGSID", belongDept.getCompany().getId(),
                "JCGSID", saleDept.getCompany().getId(),
                "CLFWDJID", SpringManager.getBean(CarServiceLevelService.class).findByCarConfigurationId(carJson.getString("jekunModelCode")).getId()
        ));
        if (resultJsonReback == null) throw new RuntimeException("获取价格失败");
        //四舍五入进位
        resultJsonReback = (JSONObject)priceRoundUp(resultJsonReback,2);

        JSONObject resultJson = new JSONObject();
        resultJson.put("dept", MapUtil.mapper("id",belongDept.getId(),"name",belongDept.getName())); //参考成本
        resultJson.put("innerReferTax", resultJsonReback.getDoubleValue("priceUnit")); //参考成本
        resultJson.put("itemId",node.getString("id")); //明细id
        resultJson.put("productId",product.getId()); //明细id
        result.add(resultJson);
        return SpringManager.getBean(ServicePlanceService.class).pageInfo(getJo,result,false);
    }

    private JSONObject getResultJson(JSONObject conditionModel, JSONObject fitting, Product product, Dept belongDept, ProductUom uom, PartyRole platform, JSONObject resultJsonReback) {
        JSONObject resultJson = new JSONObject();
        //库区额外信息
        resultJson.put("company", belongDept.getCompany());
        resultJson.put("platform", platform);
        //商品
        resultJson.put("product", product);
        resultJson.put("category", fitting.size() == 0 ? product.getCategory() : fitting);
        resultJson.put("fitting", fitting.size() == 0 ? null : fitting);
        resultJson.put("uom", uom);
        //价格
        resultJson.put("primaryPriceUnit", resultJsonReback.getDouble("primaryPriceUnit"));
        resultJson.put("primaryPriceUnitShow", resultJsonReback.getDouble("primaryPriceUnit"));
        //2022年10月26日 16:08:00 诗豪要求不要写唯一值
//        resultJson.put("uniqueValue", resultJsonReback.getString("uniqueValue"));
        resultJson.put("priceUnit", resultJsonReback.getDouble("priceUnit"));
        resultJson.put("priceApprovalAmt", resultJsonReback.getDouble("priceUnit"));
        resultJson.put("priceSource", resultJsonReback.getString("priceSource"));
        resultJson.put("state", "create");
        resultJson.put("pftPriceUnit", resultJsonReback.getDouble("pftPriceUnit"));
        resultJson.put("salesAmount", resultJsonReback.getDouble("pftPriceUnit"));
        resultJson.put("priceFlag", resultJsonReback.getDouble("priceUnit")>0);
        resultJson.put("managementFeeRate", resultJsonReback.getDouble("managementFeeRate"));
        resultJson.put("floorPrice", resultJsonReback.getDouble("floorPrice"));
        resultJson.put("clerkPriceLimit", resultJsonReback.getDouble("clerkPriceLimit"));
        resultJson.put("shopOwnerPriceLimit", resultJsonReback.getDouble("shopOwnerPriceLimit"));
        resultJson.put("csoPriceLimit", resultJsonReback.getDouble("csoPriceLimit"));
        resultJson.put("basePrice", resultJsonReback.getDouble("basePrice"));
        resultJson.put("discountRate", resultJsonReback.getDouble("discountRate").isNaN()?0:resultJsonReback.getDouble("discountRate"));
        resultJson.put("priceCostUnitInTax", resultJsonReback.getDouble("priceCostUnitInTax"));
        resultJson.put("priceCostUnitExTax", resultJsonReback.getDouble("priceCostUnitExTax"));
        resultJson.put("platformPriceCosInTax", resultJsonReback.getDouble("platformPriceCosInTax")); //平台成本价
        resultJson.put("referTax", resultJsonReback.getDoubleValue("referTax")); //参考成本
//        double fee = SpringManager.getBean(FeeRateService.class).getSupplyChainManagementFee(belongDept.getCompany().getId(), product.getClassify().getId(), "");
        resultJson.put("supplyChainManagement", Arith.round(resultJsonReback.getDouble("supplyChainManagement") * resultJsonReback.getDouble("supplyRate"),2)); //供应链管理费用
        resultJson.put("inquiryPriceUnit", resultJsonReback.getDoubleValue("inquiryPriceUnit"));
        resultJson.put("inquiryPriceLimit", resultJsonReback.getDoubleValue("inquiryPriceLimit"));
        resultJson.put("name", product.getName());
        resultJson.put("vipDiscountType", resultJsonReback.getDoubleValue("vipDiscountRate")<1?"vipDiscountRate":resultJsonReback.getDoubleValue("vipDiscountPrice")>0?"vipDiscountPrice":null);
        //前端要求需要返回的
        resultJson.put("innerBusinessKey", product.getId());
        resultJson.put("inquirySelectFlag", 1);
        resultJson.put("node", conditionModel.getJSONObject("node"));
        resultJson.put("assistType", resultJsonReback.get("assistType"));
        //单独返回默认销售数量
        resultJson.put("saleQty", 1);
        //询价单号
        resultJson.put("oldInquiryNumber", resultJsonReback.getString("oldInquiryNumber"));
        resultJson.put("expectedArrivalTime", resultJsonReback.getDouble("expectedArrivalTime"));
        resultJson.put("inquiryGooodsState", resultJsonReback.getString("inquiryGooodsState"));

        resultJson.put("supplierRemarks", resultJsonReback.getString("supplierRemarks"));
        resultJson.put("purchaseRemarks", resultJsonReback.getString("purchaseRemarks"));
        resultJson = (JSONObject)priceRoundUp(resultJson,2);
        //带安标记
        boolean productRule = ((List) this.invoke("cm.consignmentRule.findAllByCategoryAndProvinceAndCity",
                MapUtil.mapper("deptId", belongDept.getId(),
                        "categoryId", product.getCategory().getId(), "brandId", product.getBrand().getId())
        )).size() != 0;
        resultJson.put("productRule", productRule);
//        商品报价
        resultJson.put("haveOffice","暂无报价");
        List inquiryPool = servicePlanceService.getInquiryPool(conditionModel);
        resultJson = servicePlanceService.checkNowOffice(resultJson,product,belongDept,inquiryPool,resultJsonReback.getDouble("priceUnit"),productRule);

        try {
            if (conditionModel.getJSONObject("node") != null) {
                resultJson.put("higherLevelCode", conditionModel.getJSONObject("node").getJSONObject("product").getString("id"));
            }
        } catch (Exception e) {
            throw new RuntimeException("miss:nodeDie");
        }
        Location location;
        try {
            location = SpringManager.getBean(LocationService.class).findLocationByDept(belongDept, productRule);
            if (productRule) {
                if (location == null) throw new RuntimeException("门店没有设置带安虚拟库，门店名称：" + belongDept.getName());
            } else {
                if (location == null) throw new RuntimeException("未找到门店对应的仓库" + belongDept.getName());
            }
            resultJson.put("location", location);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }

        Map qryQualityInfo = this.invoke("fn.fnCommunalService.qryQualityInfo", MapUtil.mapper("SPID", product.getId(), "PLID", product.getClassify().getId(), "PPID", product.getBrand().getId()));
        if (qryQualityInfo != null) {
            resultJson.put("qualityWarranty", qryQualityInfo.get("qualityWarranty"));
            resultJson.put("qualityMileage", qryQualityInfo.get("qualityMileage"));
        }
        resultJson.put("platform", platform);

        return resultJson;
    }


    public JSONObject findProducStock(SimpleRequest request){
        JSONObject jo = request.getJO();
        String deptId = jo.getString("deptId");
        String productId = jo.getString("productId");
        Dept dept = deptRepository.findOne(deptId);
        Product product = productRepository.findOne(productId);
        JSONObject param = new JSONObject();
        param.put("OLD_DEPT_ID", dept.getOrigin());
        param.put("NEW_DEPT_ID", dept.getId());
        if (product.getCategory()!=null)param.put("CATEGORY_TEMP", product.getCategory().getId());
        param.put("PRODUCT_TEMP", product.getId());
        param.put("relationType", "yes");
        JSONArray result = servicePlanDao.queryOneProduct(param);
        if (result.size()!=0){
            JSONObject stockInfo = result.getJSONObject(0);
            return stockInfo;
        }else {
            return new JSONObject(MapUtil.mapper("TRANSFER_RECEIVE_QTY",0,
                    "TOTAL",0,
                    "SUB_STOCK",0,
                    "FROZEN_QTY",0,
                    "TRANSFER_IN_BILLING_QTY",0,
                    "PURCHASING_WAY_QTY",0,
                    "REQUIRE_BILLING_QTY",0,
                    "ID",product.getId(),
                    "USABLE_QTY",0,
                    "GENERAL_STOCK",0));
        }

    }

    /**
     * 商品匹配
     *
     * @param
     * @return
     */
    public JSONArray matchingProduct(Map jo) {
        JSONArray resultArray = new JSONArray();
        JSONObject resultJson = piManager.synErp("ipmServicePlanService.matchingProduct", MapUtil.mapper(
                "PZCXID", jo.get("PZCXID"),
                "PJMCID", jo.get("PJMCID"),
                "CJHM", jo.get("CJHM"),
                "QCCPMC", jo.get("QCCPMC"),
                "LYDJHM", jo.get("LYDJHM"),
                "LYDJMC", jo.get("LYDJMC"),
                "TYPE", jo.get("TYPE"),
                "filterCondition", jo.get("filterCondition")
        ));
        if (resultJson != null && resultJson.getString("obj") != null)
            resultArray = JSONArray.parseArray(resultJson.getString("obj"));
        return resultArray;
    }


    public Page<Map> findProductByServicePlan(SimpleRequest request) {
        String relationType = "yes";
        List<Map> filters = request.get("condition");
        String oldDeptId;
        String newDeptId;
        JSONObject param = new JSONObject();
        try {
            // fixedLossDept 定损
            // belongDept 服务
            JSONObject conditionModel = request.getJO().getJSONObject("conditionModel");
            boolean planType = conditionModel.get("fixedLossDept") != null;
            String deptId = conditionModel.get("belongDept") != null ? conditionModel.getJSONObject("belongDept").getString("id") :
                    conditionModel.get("fixedLossDept") != null ? conditionModel.getJSONObject("fixedLossDept").getString("id") : null;
            if (planType&&conditionModel.getJSONObject("orderType").getString("name").equals("委托定损")){
                deptId = conditionModel.getJSONObject("getCarDept").getString("id");
            }
            if (deptId == null) throw new RuntimeException("请传入对应的门店");

            Dept dept = deptRepository.findOne(deptId);
            oldDeptId = dept.getOrigin();
            newDeptId = dept.getId();
            Location location = SpringManager.getBean(LocationService.class).findLocationByDept(dept, false);

            ServicePlanFactory.getServicePlanMethod().setDCParam(location, param, switched);
        } catch (Exception e) {
            throw new RuntimeException("无法获取当前门店");
        }

        try {
            Map map = filters.stream().filter((item) -> {
                return "relationType".equals(item.get("field").toString());
            }).collect(Collectors.toList()).stream().findFirst().get();
            filters.remove(map);
            relationType = map.get("value").toString();

        } catch (Exception e) {
            throw new RuntimeException("是否关联车型选择有误");
        }
        JSONArray productArray;
        param.put("SIZE", request.get("size"));
        param.put("PAGE", request.get("page"));
        param.put("OLD_DEPT_ID", oldDeptId);
        param.put("NEW_DEPT_ID", newDeptId);
        param.put("relationType", relationType);
        param.put("STAR_PERSON", request.getPersonId());
        param.put("queryStock", request.getJO().get("queryStock"));
        param.put("filterCondition", request.getJO().get("filterCondition"));
        param.put("stockValid", request.getJO().get("stockValid"));

        // 拼接查询数据
        //获取配件编码
        String fittingId = "";
        for (Map item : filters) {
            Group groupTemp = new Group();
            groupTemp.setOperator("or");
            List<Filter> filtersResult = new ArrayList<>();
            if ("productTemp".equals(item.get("field").toString())) {
                param.put("PRODUCT_TEMP", item.get("value").toString());
            } else if ("specifitationTemp".equals(item.get("field").toString())) {
                param.put("SPECIFITATION_TEMP", item.get("value").toString());
            } else if ("categoryTemp".equals(item.get("field").toString())) {
                fittingId = item.get("value").toString();
                param.put("CATEGORY_TEMP", item.get("value").toString());
            } else if ("quality".equals(item.get("field").toString())) {
                JSONArray array = JSONArray.parseArray(item.get("value").toString());
                StringBuilder str = new StringBuilder();
                for (int i = 0; i < array.size(); i++) {
                    if (i == 0) {
                        str.append("'").append(array.getJSONObject(i).getString("id")).append("'");
                    } else {
                        str.append(",'").append(array.getJSONObject(i).getString("id")).append("'");
                    }
                }
                param.put("quality", str.toString());
            }
        }
        //获取用户选择得配件
        Category fitting = null;
        if (!StringUtils.isEmpty(fittingId))
            fitting = SpringManager.getBean(CategoryRepository.class).findOne(fittingId);
        // 判断查询方式
        switch (relationType) {
            case "yes":
                productArray = servicePlanDao.queryProduct(param);
                break;
            case "no_auto":
            case "no_match":
                JSONObject fnCustomerCar;
                Category category = new Category();
                try {
                    fnCustomerCar = request.getJO().getJSONObject("conditionModel").getJSONObject("customerCar");
                    if (fnCustomerCar == null) throw new RuntimeException("");
                } catch (Exception e) {
                    throw new RuntimeException("无有效车型，请检查");
                }

                try {
                    for (Map item : filters) {
                        if ("categoryTemp".equals(item.get("field").toString())) {
                            category = categoryRepository.findOne(item.get("value").toString());
                        }
                    }
                    if (category.getId() == null) throw new RuntimeException("");
                } catch (Exception e) {
                    throw new RuntimeException("关联车型查询“配件”不能为空");
                }

                if (fnCustomerCar.get("jekunModelCode") == null || fnCustomerCar.get("vin") == null)
                    throw new RuntimeException("请补全车架号或车型信息!!!");
                param.put("vin", fnCustomerCar.getString("vin"));
                param.put("jekunModelCode", fnCustomerCar.getString("jekunModelCode"));
                param.put("categoryId", category.getId());
                param.put("page", request.get("page"));
                param.put("relationType", relationType);
                SimpleRequest simpleRequest = new SimpleRequest();
                simpleRequest.setBody(param.toJSONString());
                productArray = this.commonProduct(simpleRequest);
                break;
            default:
                throw new RuntimeException("内部错误");
        }


        List<Map> resultList = productArray.stream().map(item -> {
            JSONObject itemJson = (JSONObject) item;
            Map m = MapUtil.mapped(productRepository.findOne(itemJson.getString("ID")));
            m.put("stockAmount", itemJson.getDoubleValue("STOCK_AMOUNT")); //本地库存
            m.put("subStock", itemJson.getDoubleValue("SUB_STOCK")); //区域仓
            if (productNegativeSellingService.isProductNegativeSelling(itemJson.getString("ID"))){
                m.put("generalStock", Arith.add(itemJson.getDoubleValue("GENERAL_STOCK"),99)); // 商品负卖
            }else{
                m.put("generalStock", itemJson.getDoubleValue("GENERAL_STOCK")); //本地库存
            }

            m.put("usableQTY", itemJson.getDoubleValue("USABLE_QTY"));
            m.put("frozenQTY", itemJson.getDoubleValue("FROZEN_QTY"));
            m.put("transferReceiveQty", itemJson.getDoubleValue("TRANSFER_RECEIVE_QTY"));
            m.put("purchasingWayQty", itemJson.getDoubleValue("PURCHASING_WAY_QTY"));
            m.put("transferInBillingQty", itemJson.getDoubleValue("TRANSFER_IN_BILLING_QTY"));
            m.put("requireBillingQty", itemJson.getDoubleValue("REQUIRE_BILLING_QTY"));
            if (!(itemJson.getString("CLASSIFY_ID")!=null&&itemJson.getString("CLASSIFY_ID").startsWith("M0103")))m.put("star", itemJson.getDoubleValue("STAR_FLAG"));
            return m;
        }).collect(Collectors.toList());
        for (Map map : resultList) {
            if (!ObjectUtils.isEmpty(fitting)) {
                map.put("fitting", MapUtil.mapper("id", fitting.getId(), "name", fitting.getName(), "categoryPhotos", fitting.getCategoryPhotos()));
            }
        }
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        Pageable pageable = PageRequest.of(request.get("page"), request.get("size"), sort);
        PageImpl<Map> pPage = new PageImpl<>(resultList, pageable, productArray.size() == 0 ?
                productArray.size() : productArray.getJSONObject(0).getIntValue("TOTAL"));
        return pPage;
    }

    @Listener(topic = "event:serviceToForeign.commonProduct")
    public JSONArray commonProduct(SimpleRequest simpleRequest) {
        JSONObject param = simpleRequest.getJO();
        String relationType = param.getString("relationType");
        JSONArray resultArray =
                matchingProduct(MapUtil.mapper("LYDJHM", "方案未生成",
                        "LYDJMC", "servicePlan",
                        "CJHM", param.getString("vin"),
                        "PZCXID", param.getString("jekunModelCode"),
                        "PJMCID", param.getString("categoryId"),
                        "filterCondition", param.get("filterCondition"),
                        "TYPE", relationType));

        if (resultArray.size() == 0) {
            if (param.get("queryStock") != null) return new JSONArray();
            String errorMsg = relationType.equals("no_auto") ? "匹配到商品个数为0" : "匹配到商品个数为0, 请上报数据中心";
            throw new RuntimeException(errorMsg);
        }

        List<String> list = resultArray.stream().map((item) -> {
            JSONObject json = (JSONObject) item;
            return json.getString("SPID");
        }).collect(Collectors.toCollection(ArrayList::new));

        // 确认匹配的商品是否在新框架存在
        List products = productRepository.findByIdList(list);
        if (resultArray.size() != 0 && products.size() == 0 && param.getInteger("page") == 0) {
            throw new RuntimeException("匹配商品个数：" + resultArray.size() + "，新框架商品个数：" + products.size());
        }

        String[] ids = list.stream().map(id -> "'" + id + "'").toArray(String[]::new);
        param.put("IDS", String.join(",", ids));

        JSONArray productArray = servicePlanDao.queryProduct(param);
        return productArray;
    }


    /**
     * 从老框架判断是否需要询价，需要的话，将明细模型的设置为TURE
     *
     * @param servicePlan
     * @return
     */
    public JSONObject getInquiryDetail(Map servicePlan) {
        JSONObject resultJson = piManager.synErp("ipmServicePlanService.getInquiryDetail", servicePlan);
        return resultJson;
    }

    //------------------------------工具----------------------------

    /**
     * 获取前段入参，检查
     *
     * @param simpleRequest
     * @return
     */
    private Map<String, JSONObject> getParameter(SimpleRequest simpleRequest) {
        JSONObject condition = simpleRequest.getJO().getJSONObject("condition");
        JSONObject conditionModel = simpleRequest.getJO().getJSONObject("conditionModel");
        if (condition == null || conditionModel == null)
            throw new RuntimeException("传入参数有误:condition/conditionModel,无此类型");
        return MapUtil.mapper("condition", condition, "conditionModel", conditionModel);
    }


    public void findNewIdByOldId(Map map,String enumType,String filed){
        List<Enumeration> businessCircle = SpringManager.getBean(EnumerationRepository.class).findByTypeAndValid(enumType);
        businessCircle.forEach(v ->{
            if (v.getCode().equals(map.get(filed))) {
                map.put(filed,v.getId());
            }
        });
    }
    /**
     * 获取XS51
     * @param map
     * @return
     */
    public synchronized JSONObject getXS51(Map map,boolean appFalg) {
        JSONObject returnData =new JSONObject();

        Object obj = executePriceMethod(getNewXS51Map(map));
        returnData.put("obj",obj);

        return getXS51OrXJ51(JSONObject.parseObject(returnData.getString("obj")),appFalg);
    }

    /**
     * 获取多个定价过程
     * @param simpleRequest
     * @return
     */
    public JSONObject getPriceList(SimpleRequest simpleRequest) {
        JSONObject jo = simpleRequest.getJO();
        JSONObject returnData = new JSONObject();
        JSONArray items = jo.getJSONArray("items");
        returnData.put("obj",items.stream().map(product ->{
            JSONObject productJson = (JSONObject) product;
            return executePriceMethod(productJson);
        }).collect(Collectors.toCollection(JSONArray::new)));
        return returnData;
    }


    /**
     * 获取旧系统XS51(多个商品)
     *
     * @param
     * @return
     */
    public JSONArray getXS51(List<Map> list,boolean appFalg) {
        List<JSONObject> newXJ51json = list.stream().map(map -> {
            if (map.get("uniqueIdentify") == null) {
                throw new RuntimeException("请传入唯一标识码");
            }
            return getNewXS51Map(map);
        }).collect(Collectors.toList());

        JSONObject returnData =  this.invoke("fn.service.getPriceList",MapUtil.mapper("items", newXJ51json));
        JSONArray jgArray = null;
        try {
            jgArray = JSONArray.parseArray(returnData.getString("obj"));
        } catch (Exception e) {
            throw new RuntimeException("转换错误-价格");
        }


        return jgArray.stream().map((tempJson) -> {
            JSONObject item = (JSONObject) tempJson;
            if (item.getString("P001") == null) {
                return MapUtil.mapper(
                        "uniqueIdentify", item.getString("uniqueIdentify"),
                        "primaryPriceUnit", 0,
                        "PRODUCT_NAME", item.getString("PRODUCT_NAME"),
                        "priceUnit", 0,
                        "pftPriceUnit", 0,
                        "managementFeeRate", 0,
                        "floorPrice", 0,  //最低限价
                        "clerkPriceLimit", 0,
                        "shopOwnerPriceLimit", 0,
                        "csoPriceLimit", 0,
                        "basePrice", 0,
                        "discountRate", 0,
                        "priceCostUnitInTax", 0,
                        "priceCostUnitExTax", 0,
                        "platformPriceCosInTax", 0,
                        "referTax", 0,
                        "supplyChainManagement", 0,
                        "supplyRate", 0
                );
            } else {
                return MapUtil.mapper(
                        "uniqueIdentify", item.getString("uniqueIdentify"),
                        "PRODUCT_NAME", item.getString("PRODUCT_NAME"),
                        "primaryPriceUnit", item.getDoubleValue("Z002"),
                        "priceUnit", item.getDoubleValue("S901"),
                        "pftPriceUnit", item.getDoubleValue("S901"),
                        "managementFeeRate", item.getDoubleValue("F008"),
                        "floorPrice", item.getDoubleValue("P005"),  //最低限价
                        "clerkPriceLimit", item.getDoubleValue("S801"),
                        "shopOwnerPriceLimit", item.getDoubleValue("S802"),
                        "csoPriceLimit", item.getDoubleValue("S803"),
                        "basePrice", item.getDoubleValue("P004"),
                        "discountRate", item.getDoubleValue("Z002") == 0 ? 0 : item.getDoubleValue("S901") / item.getDoubleValue("Z002"),
                        "priceCostUnitInTax", item.getDoubleValue("S950"),
                        "priceCostUnitExTax", item.getDoubleValue("S950"),
                        "platformPriceCosInTax", item.getDoubleValue("P001"),
                        "priceSource", item.getString("priceSource"),
                        "referTax", item.getDoubleValue("P008"),
                        "supplyChainManagement", (!switched?item.getDoubleValue("P006"):item.getDoubleValue("T001")) * item.getDoubleValue("P001"),     //供应链管理费用
                        "supplyRate", !switched?item.getDoubleValue("P006"):item.getDoubleValue("T001")
                );
            }
        }).collect(Collectors.toCollection(JSONArray::new));
    }


    /**
     * 获取旧系统XJ51(单个商品)
     *
     * @param map
     * @return
     */
    public JSONObject getXJ51(Map map) {
        JSONObject returnData =new JSONObject();

        Object obj = executePriceMethod(getNewXJ51map(map));
        returnData.put("obj",obj);

        if (JSONObject.parseObject(returnData.getString("obj")).getString("P001") == null) {
            return new JSONObject(MapUtil.mapper(
                    "primaryPriceUnit", 0,
                    "priceUnit", 0,
                    "pftPriceUnit", 0,
                    "managementFeeRate", 0,
                    "floorPrice", 0,  //最低限价
                    "clerkPriceLimit", 0,
                    "shopOwnerPriceLimit", 0,
                    "csoPriceLimit", 0,
                    "basePrice", 0,
                    "discountRate", 0,
                    "priceCostUnitInTax", 0,
                    "priceCostUnitExTax", 0,
                    "platformPriceCosInTax", 0,
                    "referTax", 0,
                    "supplyChainManagement", 0,     //供应链管理费用
                    "supplyRate", 0

            ));
        }

        JSONObject item = JSONObject.parseObject(returnData.getString("obj"));

        return new JSONObject(
                MapUtil.mapper(
                        "primaryPriceUnit", item.getDoubleValue("Z002"),
                        "priceUnit", item.getDoubleValue("S901"),
                        "pftPriceUnit", item.getDoubleValue("S901"),
                        "managementFeeRate", item.getDoubleValue("F008"),
                        "floorPrice", item.getDoubleValue("S903"),  //最低限价
                        "clerkPriceLimit", item.getDoubleValue("S801"),
                        "shopOwnerPriceLimit", item.getDoubleValue("S802"),
                        "csoPriceLimit", item.getDoubleValue("S803"),
                        "basePrice", item.getDoubleValue("Z002"),
                        "discountRate", item.getDoubleValue("Z002") == 0 ? 0 : item.getDoubleValue("S901") / item.getDoubleValue("Z002"),
                        "referTax", item.getDoubleValue("P008"),
                        "supplyChainManagement", item.getDoubleValue("P006") * item.getDoubleValue("S950"),     //供应链管理费用
                        "supplyRate", item.getDoubleValue("P006")
//                        "priceCostUnitInTax",item.getDouble("S950"),  //成本都由外部来
//                        "priceCostUnitExTax",item.getDouble("S950"),
//                        "platformPriceCosInTax",item.getDouble("P001")
                )
        );
    }



    public Object priceRoundUp(Object jsonObjParam, int scale) {

        Set<Map.Entry<String, Object>> entries = getEntries(jsonObjParam);

        jsonObjParam = getRoundUpDouble(scale, entries);

        return jsonObjParam;
    }

    private JSONObject getRoundUpDouble(int scale, Set<Map.Entry<String, Object>> entries) {
        JSONObject result = new JSONObject();
        for (Map.Entry<String, Object> next : entries) {
            Object value = next.getValue();
            if (value instanceof Double&&!((Double) value).isNaN()&&!((Double) value).isInfinite()) {
                result.put(next.getKey(), Arith.round((Double) value, scale, BigDecimal.ROUND_UP));
            }else if (value instanceof BigDecimal){
                BigDecimal bigDecimal = (BigDecimal) value;
                result.put(next.getKey(), Arith.round(bigDecimal.doubleValue(), scale, BigDecimal.ROUND_UP));
            }else {
                result.put(next.getKey(), value);
            }

        }
        return result;
    }

    private Set<Map.Entry<String, Object>> getEntries(Object jsonObjParam) {
        Set<Map.Entry<String, Object>> entries = null;
        if (jsonObjParam instanceof JSONObject){
            JSONObject jsonObject = (JSONObject) jsonObjParam;
            entries = jsonObject.entrySet();
        }else if (jsonObjParam instanceof com.apestech.framework.json.JSONObject){
            com.apestech.framework.json.JSONObject jsonObject = (com.apestech.framework.json.JSONObject) jsonObjParam;
            entries = jsonObject.entrySet();
        }else{
            throw new RuntimeException("获取未知类型迭代器");
        }
        return entries;
    }

    /**
     * 获取旧系统XJ51(多个商品)
     *
     * @param
     * @return
     */
    public JSONArray getXJ51(List<Map> list) {
        List<JSONObject> newXJ51map = list.stream().map(this::getNewXJ51map).collect(Collectors.toList());
        list.forEach((map) -> {
            if (map.get("uniqueIdentify") == null) {
                throw new RuntimeException("请传入唯一标识码");
            }
            getXJ51Map(map);
        });
        JSONObject returnData = this.invoke("fn.service.getPriceList",MapUtil.mapper("items", newXJ51map));
        JSONArray jgArray = null;
        try {
            jgArray = JSONArray.parseArray(returnData.getString("obj"));
        } catch (Exception e) {
            throw new RuntimeException("转换错误-价格");
        }
        return jgArray.stream().map((tempJson) -> {
            JSONObject item = (JSONObject) tempJson;
            if (item.getString("S901") == null) {
                return MapUtil.mapper(
                        "uniqueIdentify", item.getString("uniqueIdentify"),
                        "primaryPriceUnit", 0,
                        "priceUnit", 0,
                        "pftPriceUnit", 0,
                        "managementFeeRate", 0,
                        "floorPrice", 0,  //最低限价
                        "clerkPriceLimit", 0,
                        "shopOwnerPriceLimit", 0,
                        "csoPriceLimit", 0,
                        "basePrice", 0,
                        "discountRate", 0,
                        "priceCostUnitInTax", 0,
                        "priceCostUnitExTax", 0,
                        "platformPriceCosInTax", 0,
                        "supplyChainManagement", 0,     //供应链管理费用
                        "supplyRate", 0,
                        "referTax", 0 //参考成本价
                );
            } else {
                double P006 =  Arith.roundUp(item.getDoubleValue("T001"), 2);

                return MapUtil.mapper(
                        "uniqueIdentify", item.getString("uniqueIdentify"),
                        "primaryPriceUnit", item.getDoubleValue("Z002"),
                        "priceUnit", item.getDoubleValue("S901"),
                        "pftPriceUnit", item.getDoubleValue("S901"),
                        "managementFeeRate", P006,
                        "floorPrice", item.getDoubleValue("S903"),  //最低限价
                        "priceSource", item.get("priceSource"),
                        "clerkPriceLimit", item.getDoubleValue("S801"),
                        "shopOwnerPriceLimit", item.getDoubleValue("S802"),
                        "csoPriceLimit", item.getDoubleValue("S803"),
                        "basePrice", item.getDoubleValue("Z002"),
                        "discountRate", item.getDoubleValue("Z002") == 0 ? 0 : item.getDoubleValue("S901") / item.getDoubleValue("Z002"),
                        "supplyChainManagement",  item.getDoubleValue("S950"),     //供应链管理费用
                        "supplyRate", P006,
                        "referTax", item.getDoubleValue("P008"), //参考成本价
                        "supplier", item.getString("SUPPLIER_ID")
                );
            }
        }).collect(Collectors.toCollection(JSONArray::new));
    }

    /**
     * 获取XJ08map
     *
     * @param map
     * @return
     */
    public Map getXS08Map(Map map) {
        map.put("DJGCID", "XS08");
        map.put("GSID", map.get("GSID"));
        map.put("KHID", map.get("KHID"));
        map.put("SPID", map.get("SPID"));
        map.put("JLDW", map.get("JLDW"));
        return map;
    }

    /**
     * 获取新系统XJ08map
     *
     * @param map
     * @return
     */
    public JSONObject getNewXS08Map(Map map) {
        JSONObject result = new JSONObject();
        result.put("conditionStrategyId", "XS08");
        result.put("SYS_RQ", new Date());
        result.put("NOT_SPXJD_CREATE", "1");

        result.put("COMPANY_ID", map.get("GSID"));
        result.put("CUSTOMER_ID", map.get("KHID"));
        result.put("PRODUCT_ID", map.get("SPID"));
//        result.put("JLDW", map.get("JLDW") == null ? null : map.get("JLDW"));


        result.put("PRODUCT_UOM_ID", map.get("JLDWID"));
        result.put("CAR_SERVICE_LEVEL_ID", map.get("CLFWDJID"));
        result.put("ACCESS_PROVIDER_ID", map.get("JRS"));

        return result;
    }

    /**
     * 获取旧系统XS08
     *
     * @param map
     * @return
     */
    private JSONObject getXS08(Map map) {
        JSONObject returnData =new JSONObject();
        if (!switched){//集成测试环境
            //获取旧系统XS08
            returnData = piManager.synErp("ipmVipService.getDjgc", getXS08Map(map));

        }else {
            //获取新系统XS08
            JSONObject condi = getNewXS08Map(map);
            Object obj = this.invoke("condition.execConditionStrategy", condi);
            returnData.put("obj",obj);

        }
//        JSONObject returnData = piManager.synErp("ipmVipService.getDjgc", getXS08Map(map));
        if (JSONObject.parseObject(returnData.getString("obj")).getString("F051") == null)
            throw new RuntimeException(JSONObject.parseObject(returnData.getString("obj")).getString("P_MSG"));

        JSONObject re1 = JSONObject.parseObject(returnData.getString("obj"));
        //
        return new JSONObject(MapUtil.mapper(
                "primaryPriceUnit", re1.getDoubleValue("F051"),
                "priceUnit", re1.getDoubleValue("F051"),
                "pftPriceUnit", re1.getDoubleValue("F051"),
                "managementFeeRate", 0,
                "floorPrice", re1.getDoubleValue("F051"),  //最低限价
                "clerkPriceLimit", re1.getDoubleValue("F051"),
                "shopOwnerPriceLimit", re1.getDouble("F051"),
                "csoPriceLimit", re1.getDoubleValue("F051"),
                "basePrice", re1.getDoubleValue("F051"),
                "discountRate", re1.getDoubleValue("F051") / re1.getDoubleValue("F051"),
                "priceCostUnitInTax", 0,
                "priceCostUnitExTax", 0,
                "platformPriceCosInTax", 0
        ));
    }

    public JSONArray getXS08(List<Map> list) {
        List<JSONObject> newXS08json = list.stream().map(map -> {
            return getNewXS08Map(map);
        }).collect(Collectors.toList());

        list.forEach((map) -> {
            if (map.get("uniqueIdentify") == null) {
                throw new RuntimeException("请传入唯一标识码");
            }
            getXS08Map(map);
        });
        JSONObject returnData = !switched?
                piManager.synErp("ipmVipService.getDjgcArray", MapUtil.mapper("items", list)):
                this.invoke("fn.service.getPriceList",MapUtil.mapper("items", newXS08json));
        JSONArray jgArray = null;
        try {
            jgArray = JSONArray.parseArray(returnData.getString("obj"));
        } catch (Exception e) {
            throw new RuntimeException("转换错误-价格");
        }
        return jgArray.stream().map((tempJson) -> {
            JSONObject item = (JSONObject) tempJson;
            if (item.getString("F051") == null) {
                return MapUtil.mapper(
                        "uniqueIdentify", item.getString("uniqueIdentify"),
                        "primaryPriceUnit", 0,
                        "priceUnit", 0,
                        "pftPriceUnit", 0,
                        "managementFeeRate", 0,
                        "floorPrice", 0,  //最低限价
                        "clerkPriceLimit", 0,
                        "shopOwnerPriceLimit", 0,
                        "csoPriceLimit", 0,
                        "basePrice", 0,
                        "discountRate", 0,
                        "priceCostUnitInTax", 0,
                        "priceCostUnitExTax", 0,
                        "platformPriceCosInTax", 0
                );
            } else {
                return MapUtil.mapper(
                        "uniqueIdentify", item.getString("uniqueIdentify"),
                        "primaryPriceUnit", item.getDoubleValue("F051"),
                        "priceUnit", item.getDoubleValue("F051"),
                        "pftPriceUnit", item.getDoubleValue("F051"),
                        "managementFeeRate", 0,
                        "floorPrice", item.getDoubleValue("F051"),  //最低限价
                        "clerkPriceLimit", item.getDoubleValue("F051"),
                        "shopOwnerPriceLimit", item.getDoubleValue("F051"),
                        "csoPriceLimit", item.getDoubleValue("F051"),
                        "basePrice", item.getDoubleValue("F051"),
                        "discountRate", item.getDoubleValue("F051") / item.getDoubleValue("F051"),
                        "priceCostUnitInTax", 0,
                        "priceCostUnitExTax", 0,
                        "platformPriceCosInTax", 0
                );
            }
        }).collect(Collectors.toCollection(JSONArray::new));
    }

    /**
     * 获取GS01(单个)
     *
     * @param map
     * @return
     */
    public JSONObject getGS51(Map map) {
        JSONObject returnData = new JSONObject();

        //获取新系统GS51
        Object obj = executePriceMethod(getNewGS51Map(map));
        returnData.put("obj",obj);

        return getGS51PriceItem(returnData.getString("obj"));

    }

    /**
     * 获取旧系统GS01(多个)
     *
     * @param
     * @return
     */
    public JSONArray getGS51(List<Map> maps) {
        List<JSONObject> newGS51json = maps.stream().map(this::getNewGS51Map).collect(Collectors.toList());
        maps.forEach((map) -> {
            if (map.get("uniqueIdentify") == null) {
                throw new RuntimeException("请传入唯一标识码");
            }
            getGS51Map(map);
        });

        JSONObject returnData = this.invoke("fn.service.getPriceList",MapUtil.mapper("items", newGS51json));
        JSONArray jgArray = null;
        try {
            jgArray = JSONArray.parseArray(returnData.getString("obj"));
        } catch (Exception e) {
            throw new RuntimeException("转换错误-价格");
        }
        return jgArray.stream().map((tempJson) -> {
            JSONObject item = (JSONObject) tempJson;
            if (item.getString("S950") == null) {
                return MapUtil.mapper(
                        "uniqueIdentify", item.getString("uniqueIdentify"),
                        "primaryPriceUnit", 0,
                        "priceUnit", 0,
                        "pftPriceUnit", 0,
                        "managementFeeRate", 0,
                        "floorPrice", 0,  //最低限价
                        "clerkPriceLimit", 0,
                        "shopOwnerPriceLimit", 0,
                        "csoPriceLimit", 0,
                        "basePrice", 0,
                        "discountRate", 0,
                        "priceCostUnitInTax", 0,
                        "priceCostUnitExTax", 0,
                        "platformPriceCosInTax", 0,
                        "referTax", 0,
                        "supplyChainManagement", 0,     //供应链管理费用
                        "supplyRate", 0
                );
            } else {
                double P006 = !switched ? Arith.roundUp(item.getDoubleValue("P006"), 2) : Arith.roundUp(item.getDoubleValue("T001"), 2);
                return MapUtil.mapper(
                        "uniqueIdentify", item.getString("uniqueIdentify"),
                        "primaryPriceUnit", Arith.roundUp(item.getDoubleValue("S950"), 2),
                        "priceUnit", Arith.roundUp(item.getDoubleValue("S950"), 2),
                        "pftPriceUnit", Arith.roundUp(item.getDoubleValue("S950"), 2),
                        "managementFeeRate", P006,
                        "floorPrice", Arith.roundUp(item.getDoubleValue("S950"), 2),  //最低限价
                        "clerkPriceLimit", Arith.roundUp(item.getDoubleValue("S950"), 2),
                        "priceSource", item.get("priceSource"),
                        "shopOwnerPriceLimit", Arith.roundUp(item.getDoubleValue("S950"), 2),
                        "csoPriceLimit", Arith.roundUp(item.getDoubleValue("S950"), 2),
                        "basePrice", Arith.roundUp(item.getDoubleValue("S950"), 2),
                        "discountRate", Arith.roundUp(item.getDoubleValue("S950"), 2) / Arith.roundUp(item.getDoubleValue("S950"), 2),
                        "priceCostUnitInTax", Arith.roundUp(item.getDoubleValue("P009"), 2),
                        "priceCostUnitExTax", Arith.roundUp(item.getDoubleValue("P009"), 2),
                        "platformPriceCosInTax", Arith.roundUp(item.getDoubleValue("P001"), 2),
                        "referTax", Arith.roundUp(item.getDoubleValue("P008"), 2),
                        "supplyChainManagement", Arith.roundUp( item.getDoubleValue("P009"), 2),     //供应链管理费用
                        "supplier",item.getString("SUPPLIER_ID") ,     //供应链管理费用
                        "supplyRate", P006
                );
            }
        }).collect(Collectors.toCollection(JSONArray::new));
    }


    /**
     * 获取旧系统GS01(单个)
     *
     * @param map
     * @return
     */
    public JSONObject getGS52(Map map) {
        JSONObject returnData =new JSONObject();
        if (!switched){//集成测试环境
            //获取旧系统XS51
            returnData = piManager.synErp("ipmVipService.getDjgc", getGS52Map(map));

        }else {
            //获取新系统XS51
            JSONObject condi = getNewGS52Map(map);
            Object obj = this.invoke("condition.execConditionStrategy", condi);
            returnData.put("obj",obj);
        }


        if (JSONObject.parseObject(returnData.getString("obj")).getString("S950") == null) {
            return new JSONObject(MapUtil.mapper(
                    "priceCostUnitInTax", 0,
                    "priceCostUnitExTax", 0
            ));
        }

        JSONObject re1 = JSONObject.parseObject(returnData.getString("obj"));
        //
        return new JSONObject(MapUtil.mapper(
                "priceCostUnitInTax", re1.getDouble("S950"),
                "priceCostUnitExTax", re1.getDouble("S950")
        ));
    }

    /**
     * 获取旧系统GS02(多个)
     *
     * @param
     * @return
     */
    public JSONArray getGS52(List<Map> maps) {
        List<JSONObject> newGS52json = maps.stream().map(map -> {
            return getNewGS52Map(map);
        }).collect(Collectors.toList());

        maps.forEach((map) -> {
            if (map.get("uniqueIdentify") == null) {
                throw new RuntimeException("请传入唯一标识码");
            }
            getGS52Map(map);
        });

        JSONObject returnData = !switched?
                piManager.synErp("ipmVipService.getDjgcArray", MapUtil.mapper("items", maps)):
                this.invoke("fn.service.getPriceList",MapUtil.mapper("items", newGS52json));
        JSONArray jgArray = null;
        try {
            jgArray = JSONArray.parseArray(returnData.getString("obj"));
        } catch (Exception e) {
            throw new RuntimeException("转换错误-价格");
        }
        return jgArray.stream().map((tempJson) -> {
            JSONObject item = (JSONObject) tempJson;
            if (item.getString("S950") == null) {
                return MapUtil.mapper(
                        "uniqueIdentify", item.getString("uniqueIdentify"),
                        "priceCostUnitInTax", 0,
                        "priceCostUnitExTax", 0
                );
            } else {
                return MapUtil.mapper(
                        "uniqueIdentify", item.getString("uniqueIdentify"),
                        "priceCostUnitInTax", item.getDouble("S950"),
                        "priceCostUnitExTax", item.getDouble("S950")
                );
            }
        }).collect(Collectors.toCollection(JSONArray::new));
    }


    /**
     * 对单个商品查询，提供给前端界面操作
     * 传入值：
     * NEW_DEPT_ID
     * productList  数组
     *
     * @param req
     * @return
     */
    public JSONObject queryProductStoreForListOne(SimpleRequest req) {
        JSONObject jo = req.getJO();
        try {
            String origin = deptRepository.findOne(jo.getString("NEW_DEPT_ID")).getOrigin();
            if (origin == null || "".equals(origin.trim())) throw new RuntimeException("");
            jo.put("OLD_DEPT_ID", origin);
        } catch (Exception e) {
            throw new RuntimeException("该门店主数据有问题，请检查门店是否存在（包括老系统门店编码信息）");
        }
        JSONArray array = servicePlanDao.queryProductStoreForList(jo);
        if (array.size() != 1) throw new RuntimeException("根据商品编码找到多个商品或者没找到商品");
        return array.getJSONObject(0);
    }

    /**
     * 对多个商品查询
     * NEW_DEPT_ID
     * productList  数组
     *
     * @param req
     * @return
     */
    public JSONArray queryProductStoreForList(SimpleRequest req) {
        JSONObject jo = req.getJO();
        try {
            String origin = deptRepository.findOne(jo.getString("NEW_DEPT_ID")).getOrigin();
            if (origin == null || "".equals(origin.trim())) throw new RuntimeException("");
            jo.put("OLD_DEPT_ID", origin);
        } catch (Exception e) {
            throw new RuntimeException("该门店主数据有问题，请检查门店是否存在（包括老系统门店编码信息）");
        }
        JSONArray array = servicePlanDao.queryProductStoreForList(jo);
        return array == null ? new JSONArray() : array;
    }

    /**
     * @param request
     * @return
     */
    public Page<Map> queryEmployeeByBranchId(SimpleRequest request) {
        request = request.getO(SimpleRequest.class);
        String postId = request.getPostId();
        if (postId == null) throw new RuntimeException("请设置对应的post信息");

        String branch = getSelectDeptBranch(request, postId);

        JSONObject param = new JSONObject();
        param.put("SIZE", request.get("size"));
        param.put("PAGE", request.get("page"));
        param.put("branchId", branch);
        param.put("condition", createConditonForSalmanin(request));
        JSONArray array = servicePlanDao.queryEmployeeByBranchId(param);

        List<Map> resultList = array.stream().map(item -> {
            JSONObject tempJson = (JSONObject) item;
            return MapUtil.mapper("id", tempJson.getString("ID"), "name", tempJson.getString("NAME"),"groupBy","post","post",tempJson.getString("POST_NAME"));
        }).collect(Collectors.toList());
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        Pageable pageable = PageRequest.of(request.get("page"), request.get("size"), sort);
        PageImpl<Map> pPage = new PageImpl<>(resultList, pageable, resultList.size() == 0 ?
                resultList.size() : array.getJSONObject(0).getIntValue("TOTAL"));
        return pPage;
    }

    private String getSelectDeptBranch(SimpleRequest request, String postId) {
        Post post = null;
        post = SpringManager.getBean(PostRepository.class).findOne(postId);
        Dept dept = null;
        try {
            JSONArray jsonArray =null;
            try {
                jsonArray = request.getJO().getJSONObject("group").getJSONArray("filters");
            } catch (Exception e) {
                jsonArray = request.getJO().getJSONObject("domain").getJSONArray("filters");
            }
            for (Object o : jsonArray) {
                JSONObject jsonObject = (JSONObject) o;
                if (jsonObject.getString("field").equals("dept")){
                    dept = SpringManager.getBean(DeptRepository.class).findOne(jsonObject.getString("value"));
                }
            }
        } catch (Exception e) {
        }
        if (post == null&&dept==null) throw new RuntimeException("请设置对应的post信息");
        return dept==null?post.getBranch().getId():dept.getBranch().getId();
    }

    private String createConditonForSalmanin(SimpleRequest request) {
        String condition = "";
        List<Filter> list = JpaDsl.getGroup(request).getFilters();
        if (list != null && list.size() != 0) {
            List<Filter> resultList = list.stream().filter(filter -> {
                return filter.getValue() != null && !"".equals(filter.getValue().toString().trim());
            }).collect(Collectors.toList());

            for (int i = 0; i < resultList.size(); i++) {
                Filter filter = list.get(i);
                if ("person.id".equals(filter.getField())) {
                    if (condition.trim().equals("")) {
                        condition = condition + "B.ID LIKE '%" + filter.getValue() + "%'";
                    } else {
                        condition = condition + " or B.ID LIKE '%" + filter.getValue() + "%'";
                    }
                }
                if ("person.party.name".equals(filter.getField())) {
                    if (condition.trim().equals("")) {
                        condition = condition + "C.NAME LIKE '%" + filter.getValue() + "%'";
                    } else {
                        condition = condition + " or C.NAME LIKE '%" + filter.getValue() + "%'";
                    }
                }
            }
            if (!condition.trim().equals("")) {
                condition = "AND (" + condition + ")";
            }
        }
        return condition;
    }

    /***
     * 获取部门所有的人员并转化为partyRole
     *
     * condition 为空的时候，查本店
     * condition 不为空的时候，再点的为空
     */
    public Page<Map> findAllPartyRole(SimpleRequest request) {
        JSONObject jo = request.getJO();
        JSONArray condition = jo.getJSONArray("condition");
        Object inShop = null;
        if (condition != null) {
            inShop = condition.stream().map(item -> {
                JSONObject tempJson = JSON.parseObject(JSONObject.toJSONString(item));
                return tempJson.getString("value");
            }).findFirst().orElse(null);
        }

        if (inShop == null) {
            return this.invoke("aut.user.findAllPartyRoleInShop", request);
        } else if (inShop.equals("inShop")){
            return this.invoke("aut.user.findAllPartyRoleInner", request);
        }else {
            return this.invoke("aut.user.findAllPartyRoleByOrder", request);
        }
    }

    // 服务方案装配图导入商品获取价格，暂时都默认为0
    @Listener(topic = "event:serviceToForeign.appendJGInfo")
    public JSONObject appendJGInfo(SimpleRequest simpleRequest) {
        JSONObject getJo = simpleRequest.getJO();
        JSONObject condition = getJo.getJSONObject("condition");
        JSONObject conditionModel = getJo.getJSONObject("conditionModel");

        Product product = getProduct(condition);
        
        Dept belongDept = deptRepository.findOne(judgeString("belongDept", "id", conditionModel));
        JSONObject fitting = new JSONObject();
        if (condition.containsKey("fitting")) fitting = condition.getJSONObject("fitting");

        ProductUom uom = new ProductUom();
        try {
            uom = productUomRepository.findAll(
                    JpaDsl.toCriteriaByEq("uomCategory.id", product.getUom().getUomCategory().getId(), "saleFirst", true)
            ).stream().findFirst().get();
        } catch (Exception e) {
            throw new RuntimeException("系统中不存在该商品默认销售计量单位:" + uom.getName());
        }

        JSONObject resultJson = new JSONObject();
        PartyRole platform = SpringManager.getBean(FnCommunalService.class).getPlatform(false, true, belongDept, product);
        //库区额外信息
        resultJson.put("company", belongDept.getCompany());
        resultJson.put("platform", platform);
        //商品
        resultJson.put("product", product);
        resultJson.put("category", fitting.size() == 0 ? product.getCategory() : fitting);
        resultJson.put("fitting", fitting.size() == 0 ? null : fitting);
        resultJson.put("uom", uom);
        //价格
        resultJson.put("primaryPriceUnit", 0);
        resultJson.put("primaryPriceUnitShow", 0);
        resultJson.put("priceUnit", 0);
        resultJson.put("pftPriceUnit", 0);
        resultJson.put("managementFeeRate", 0);
        resultJson.put("floorPrice", 0);
        resultJson.put("clerkPriceLimit", 0);
        resultJson.put("shopOwnerPriceLimit", 0);
        resultJson.put("csoPriceLimit", 0);
        resultJson.put("basePrice", 0);
        resultJson.put("discountRate", 0);
        resultJson.put("priceCostUnitInTax", 0);
        resultJson.put("priceCostUnitExTax", 0);
        resultJson.put("platformPriceCosInTax", 0); //平台成本价
        resultJson.put("referTax", 0); //参考成本
        resultJson.put("supplyChainManagement", 0); //供应链管理费用
        //前端要求需要返回的
        resultJson.put("innerBusinessKey", product.getId());
        resultJson.put("inquirySelectFlag", 1);
        //单独返回默认销售数量
        resultJson.put("saleQty", 1);
        //询价单号
        resultJson.put("oldInquiryNumber", null);
        resultJson.put("expectedArrivalTime", null);
        resultJson.put("inquiryGooodsState", null);

        resultJson.put("supplierRemarks", null);
        resultJson.put("purchaseRemarks", null);
        //带安标记
        boolean productRule = ((List) this.invoke("cm.consignmentRule.findAllByCategoryAndProvinceAndCity",
                MapUtil.mapper("deptId", belongDept.getId(),
                        "categoryId", product.getCategory().getId(), "brandId", product.getBrand().getId())
        )).size() != 0;
        resultJson.put("productRule", productRule);
        try {
            Location location;
            location = SpringManager.getBean(LocationService.class).findLocationByDept(belongDept, productRule);
            if (productRule) {
                if (location == null) throw new RuntimeException("门店没有设置带安虚拟库，门店名称：" + belongDept.getName());
            } else {
                if (location == null) throw new RuntimeException("未找到门店对应的仓库" + belongDept.getName());
            }
            resultJson.put("location", location);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
        Map qryQualityInfo = this.invoke("fn.fnCommunalService.qryQualityInfo", MapUtil.mapper("SPID", product.getId(), "PLID", product.getClassify().getId(), "PPID", product.getBrand().getId()));
        if (qryQualityInfo != null) {
            resultJson.put("qualityWarranty", qryQualityInfo.get("qualityWarranty"));
            resultJson.put("qualityMileage", qryQualityInfo.get("qualityMileage"));
        }
        resultJson.put("platform", platform);
        return resultJson;
    }

    public JSONArray qryXJInfoFromOldSys(List<String> list) {
        JSONObject json = piManager.synErp("ipmServicePlanService.qryXJInfoFromOldSys", MapUtil.mapper("items", list));
        return JSONArray.parseArray(json.getString("obj"));
    }

    public boolean checkMotorcycleType(SimpleRequest re) {
        try {
            //车辆数据
            JSONObject carJson = re.getJO().getJSONObject("customerCar");
            return SpringManager.getBean(CarConfigurationService.class).isStopService(carJson.getString("jekunModelCode"));
        } catch (Exception e) {
            //标记打回来
            e.printStackTrace();
            return false; //非停止
        }
    }

    /**
     * 获取旧系统XS51(多个商品)
     *
     * @param
     * @return
     */
    public JSONArray getCG01(List<Map> list) {
        List<JSONObject> newCG01json = list.stream().map(map -> {
            return getNewCG01Map(map);
        }).collect(Collectors.toList());

        list.forEach((map) -> {
            if (map.get("uniqueIdentify") == null) {
                throw new RuntimeException("请传入唯一标识码");
            }
            getCG01Map(map);
        });
        JSONObject returnData = !switched?
                piManager.synErp("ipmVipService.getDjgcArray", MapUtil.mapper("items", list)):
                this.invoke("fn.service.getPriceList",MapUtil.mapper("items", newCG01json));
        JSONArray jgArray = null;
        try {
            jgArray = JSONArray.parseArray(returnData.getString("obj"));
        } catch (Exception e) {
            throw new RuntimeException("转换错误-价格");
        }


        return jgArray.stream().map((tempJson) -> {
            JSONObject item = (JSONObject) tempJson;
            if (item.getString("P001") == null) {
                return MapUtil.mapper(
                        "uniqueIdentify", item.getString("uniqueIdentify"),
                        "P001", 0
                );
            } else {
                return MapUtil.mapper(
                        "uniqueIdentify", item.getString("uniqueIdentify"),
                        "P001", item.getDoubleValue("P001")
                );
            }
        }).collect(Collectors.toCollection(JSONArray::new));
    }

    @Listener(topic = "event:retail.annualAudit.getPrice")
    public JSONArray obtainAnnualAuditPrice(SimpleRequest re) {
        List<Map> paramLsit = Optional.ofNullable(re.getJA().stream().map(item -> {
            return (Map) MapUtil.mapped(item);
        }).collect(Collectors.toList())).orElseThrow(() -> new RuntimeException("传入参数为空"));
        return getCG01(paramLsit);
    }

    public Page<Map> findProductBySaleOrder(SimpleRequest request) {
        String relationType = "yes";
        List<Map> filters = request.get("condition");
        String oldDeptId;
        String newDeptId;
        JSONObject param = new JSONObject();
        JSONObject conditionModel = request.getJO().getJSONObject("conditionModel");

        String locationId = conditionModel.getJSONObject("location").getString("id");
        Location location = locationRepository.findOne(locationId);
        try {
            Dept dept = location.getDept();
            if (Objects.isNull(dept)){
                String deptId = conditionModel.getJSONObject("dept").getString("id");
                if (deptId == null){
                    throw new RuntimeException("请传入对应的门店");
                }
                dept = deptRepository.findOne(deptId);
            }
            oldDeptId = dept.getOrigin();
            newDeptId = dept.getId();
            ServicePlanFactory.getServicePlanMethod().setDCParam(location, param, switched);
        } catch (Exception e) {
            throw new RuntimeException("无法获取当前门店");
        }


        param.put("SIZE", request.get("size"));
        param.put("PAGE", request.get("page"));
        param.put("OLD_DEPT_ID", oldDeptId);
        param.put("NEW_DEPT_ID", newDeptId);
        param.put("relationType", relationType);
        param.put("queryStock", request.getJO().get("queryStock"));
        param.put("filterCondition", request.getJO().get("filterCondition"));

        // 拼接查询数据
        //获取配件编码
        String fittingId = "";
        for (Map item : filters) {
            Group groupTemp = new Group();
            groupTemp.setOperator("or");
            if ("productTemp".equals(item.get("field").toString())) {
                param.put("PRODUCT_TEMP", item.get("value").toString());
            } else if ("productClassify".equals(item.get("field").toString())) {
                param.put("PRODUCT_CLASSIFY", item.get("value").toString());
            } else if ("productBrand".equals(item.get("field").toString())) {
                param.put("PRODUCT_BRAND", item.get("value").toString());
            } else if ("quality".equals(item.get("field").toString())) {
                JSONArray array = JSONArray.parseArray(item.get("value").toString());
                StringBuilder str = new StringBuilder();
                for (int i = 0; i < array.size(); i++) {
                    if (i == 0) {
                        str.append("'").append(array.getJSONObject(i).getString("id")).append("'");
                    } else {
                        str.append(",'").append(array.getJSONObject(i).getString("id")).append("'");
                    }
                }
                param.put("quality", str.toString());
            }
        }
        //获取用户选择得配件
        Category fitting = null;
        if (!StringUtils.isEmpty(fittingId))
            fitting = SpringManager.getBean(CategoryRepository.class).findOne(fittingId);
        //判断仓库是否为门店仓库
        JSONArray productArray;
        param.put("PRODUCT_GROUP","50");
        if (Objects.equals(location.getDepot().getDepotLevel().getId(),"000122")) {
            productArray = servicePlanDao.queryProduct(param);
        }else {
            param.put("NEW_LOCATION_ID", locationId);
            productArray = servicePlanDao.queryProductBySale(param);
        }


        List<Map> resultList = productArray.stream().map(item -> {
            JSONObject itemJson = (JSONObject) item;
            Map m = MapUtil.mapped(productRepository.findOne(itemJson.getString("ID")));
            m.put("stockAmount", itemJson.getDoubleValue("STOCK_AMOUNT")); //本地库存
            m.put("subStock", itemJson.getString("SUB_STOCK") != null ? itemJson.getDoubleValue("SUB_STOCK") : "-"); //区域仓
            m.put("generalStock", itemJson.getString("SUB_STOCK") != null ? itemJson.getDoubleValue("GENERAL_STOCK"): "-"); //本地库存

            m.put("usableQTY", itemJson.getDoubleValue("USABLE_QTY"));
            m.put("frozenQTY", itemJson.getDoubleValue("FROZEN_QTY"));
            m.put("transferReceiveQty", itemJson.getDoubleValue("TRANSFER_RECEIVE_QTY"));
            m.put("purchasingWayQty", itemJson.getDoubleValue("PURCHASING_WAY_QTY"));
            m.put("transferInBillingQty", itemJson.getDoubleValue("TRANSFER_IN_BILLING_QTY"));
            m.put("requireBillingQty", itemJson.getDoubleValue("REQUIRE_BILLING_QTY"));
            return m;
        }).collect(Collectors.toList());
        for (Map map : resultList) {
            if (!ObjectUtils.isEmpty(fitting)) {
                map.put("fitting", MapUtil.mapper("id", fitting.getId(), "name", fitting.getName(), "categoryPhotos", fitting.getCategoryPhotos()));
            }
        }
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        Pageable pageable = PageRequest.of(request.get("page"), request.get("size"), sort);
        PageImpl<Map> pPage = new PageImpl<>(resultList, pageable, productArray.size() == 0 ?
                productArray.size() : productArray.getJSONObject(0).getIntValue("TOTAL"));
        return pPage;
    }

    /**
     * 传入方案ID 商品id 定价过程 返回结果和入参
     * @param simpleRequest
     * @return
     */
    public JSONObject findPlanProductPriceCondition(SimpleRequest simpleRequest){
        JSONObject jo = simpleRequest.getJO();
        String planId = jo.getString("planId");
        String productId = jo.getString("productId");
        String djgc = (String) jo.getOrDefault("DJGC","XS51");
        Double kys = (Double) jo.getOrDefault("KYS", 1.0);
        JSONObject result = new JSONObject();

        ServicePlan servicePlan = servicePlanRepository.findOne(planId);
        List<ServicePlanItem> servicePlanItems = servicePlan.getServicePlanItems().stream().filter(servicePlanItem -> servicePlanItem.getProduct().getId().equals(productId)).collect(Collectors.toList());
        if (servicePlanItems.isEmpty()) throw new RuntimeException("没有该商品!!");
        if (servicePlanItems.size()>1) throw new RuntimeException("重复商品!");
        ServicePlanItem servicePlanItem = servicePlanItems.get(0);
        PartyRole platform = servicePlanItem.getPlatform() == null ? SpringManager.getBean(FnCommunalService.class).getPlatform(false, true, servicePlan.getBelongDept(), servicePlanItem.getProduct()) : servicePlanItem.getPlatform();

        JSONObject condition =new ConditionBuilder.Builder(djgc)
                .setDept(servicePlan.getBelongDept())
                .setPlatform(platform)
                .fnCustomer(servicePlan.getCustomerCar())
                .product(servicePlanItem.getProduct())
                .setProductUomId(servicePlanItem.getUom().getId())
                .setCooperationType(servicePlan.getCooperationType())
                .setUsableQty(kys)
                .build()
                .toJsonObject();

        Object o = executePriceMethod(condition);

        JSONObject priceInfo = getXS51OrXJ51(JSONObject.parseObject(o.toString()),true);

        result.put("condition",condition);
        result.put("returnJson",o);
        result.put("priceInfo",priceInfo);
        return result;

    }

    public Map getGS51Map(ServicePlan servicePlan,Product product,ProductUom uom){
        PartyRole platform = SpringManager.getBean(FnCommunalService.class).getPlatform(false, true, servicePlan.getBelongDept(), product);
        return getGS51Map(servicePlan.getBelongDept(),servicePlan.getSaleDept(),product,platform,uom,new JSONObject(servicePlan.getCustomer()),new JSONObject(servicePlan.getCustomerCar()));
    }

    public Map getXS51Map(ServicePlan servicePlan,Product product,ProductUom uom,Double planKys){
        PartyRole platform = SpringManager.getBean(FnCommunalService.class).getPlatform(false, true, servicePlan.getBelongDept(), product);
        return getXS51Map(servicePlan.getBelongDept(), product,servicePlan.getCooperationType(),new JSONObject(servicePlan.getCustomerCar()),new JSONObject(servicePlan.getCustomer()),platform,uom,planKys);
    }

    /**
     * APP传递[门店/会员手机号/会员类型/车牌/配置车型/商品编码至ERP，ERP返回某商品编码的销售价格
     * @param request
     * @return
     */
    private List<JSONObject> findProductPriceForApp(SimpleRequest request){
        JSONObject jo = request.getJO();
        Dept dept = deptRepository.findOne(jo.getString("deptId"));
        if (dept==null)throw new RuntimeException("门店不存在");
        JSONArray productList = jo.getJSONArray("productList");
        if (productList.isEmpty())throw new RuntimeException("请至少填入一个商品编码");
        String jrs = SpringManager.getBean(AccessProviderRepository.class).findByCompany(dept.getCompany().getId()).getId();
        List<JSONObject> resultList = productList.stream().map(o -> {
            JSONObject jsonObject = (JSONObject) o;
            Product product = productRepository.findOne(jsonObject.getString("productId"));
            if (product == null) throw new RuntimeException("不存在商品编码为:" + jsonObject.getString("productId") + "的商品");
            PartyRole platform = SpringManager.getBean(FnCommunalService.class).getPlatform(false, true, dept, product);
            JSONObject resultJson = new ConditionBuilder.Builder("XS51")
                    .setDept(dept)
                    .product(product)
//                    .fnCustomer(customerCar)
                    .setPhoneNumber(jo.getString("phoneNumber"))
                    .setAccessProviderId(jrs)
                    .setCarServiceLevelId((SpringManager.getBean(CarServiceLevelService.class).findByCarConfigurationId(jo.getString("jekunModelCode"))).getId())
                    .setCarLicense(jo.getString("carLicense"))
                    .setVipLevelId(jo.getString("level"))
                    .setCustomerId(jo.getString("customerId"))
                    .setVipIdentityId(jo.getString("vipIdentityId"))
                    .setPlatform(platform)
                    .setSysNoCheck("SUPPLIER_ID")
                    .setProductUomId(product.getUom().getId())
                    .setUsableQty(0D).build().execConditionStrategy().getResultJson();
            resultJson.put("Amount",jsonObject.getInteger("number")*resultJson.getDoubleValue("S901"));
            return resultJson;
        }).collect(Collectors.toList());

        return resultList;

    }

    /**
     * 返回符合条件的询价商品
     * @param serviceplanMap
     * @param predicate
     */
    public JSONObject getInquiryPoolProduct(Map serviceplanMap,  Predicate<JSONObject> predicate){
        Map invoke = this.invoke("commodityInquiry.order.getInquiryPool", serviceplanMap);
        List item = (List) invoke.get("item");
        JSONObject resultJson = new JSONObject();
        for (Object o : item) {
            //原商品
            Map ysp = (Map) o;
            //询价商品
            List xjspList = (List) ysp.get("item");
            for (Object xjsp : xjspList) {
                JSONObject xjspJson = new JSONObject((Map) xjsp);
                if (predicate.test(xjspJson)) {
                    if (!resultJson.isEmpty()){
                        throw new RuntimeException("结果存在多条,请确认条件是否足够");
                    }
                    resultJson = xjspJson;
                }
            }
        }
        return resultJson;
    }
    public JSONObject addUseNumber(SimpleRequest request){
        JSONObject jo = request.getJO();
        JSONObject condition = jo.getJSONObject("condition");
        Product product = getProduct(condition);
        StarProduct starProduct = starProductRepository.findByProductAndStarPerson(product, request.getPerson());
        starProduct.setUseNumber(starProduct.getUseNumber()+1);
        starProductRepository.saveAndFlush(starProduct);
        return jo;
    }

    public Map calculateCommissionForKN(SimpleRequest request){
        JSONObject jo = request.getJO();
        double purchasePrice = jo.getDoubleValue("purchasePrice");//采购单价
//        double suggestPrice = jo.getDoubleValue("suggestPrice");//建议售价
        String supplierId = jo.getString("supplierId");//供应商
        String productId = jo.getString("productId");//商品编码
        String deptId = jo.getString("deptId");//部门
        Dept dept = deptRepository.findOne(deptId);
        if (dept==null)throw new RuntimeException("["+deptId+"]门店不存在");
        String operator2 = "";
        try {
            PartyRole operator = dept.getCompany().getParty().getPatyRoleByType("Operator");
            operator2 = operator.getId();
        } catch (Exception e) {
            e.printStackTrace();
        }
//        Store store = SpringManager.getBean(StoreRepository.class).findByDept(dept);
//        Merchant merchant = store.getMerchant();
        JSONObject js02 = new ConditionBuilder.Builder("JS02")
                .setSupplierId(supplierId)
                .setProductId(productId)
                .setMerchantId(operator2)
                .setP001(purchasePrice)
                .build()
                .execConditionStrategy()
                .formatAmount()
                .getResultJson();
        double deptPurchasePrice = Arith.round(js02.getDoubleValue("P118"),0);//门店采购价
        double operatorCommission  = Arith.round(js02.getDoubleValue("P119"),2);//运营商佣金
        double JekunAutoCommission = Arith.round(Arith.sub(deptPurchasePrice,purchasePrice),2);//车宝佣金

        return mapper(
                "deptPurchasePrice",deptPurchasePrice,
                "operatorCommission",operatorCommission,
                "JekunAutoCommission",JekunAutoCommission
        );

    }
}
